package com.itheima.service.impl;

import com.itheima.mapper.UserMapper;
import com.itheima.pojo.User;
import com.itheima.pojo.query.PageQuery;
import com.itheima.pojo.vo.PageResult;
import com.itheima.pojo.vo.UserLoginVo;
import com.itheima.service.UserService;
import com.itheima.utils.JwtUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequiredArgsConstructor
@Service
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;

    /***
     * 登录流程
     * @param user
     * @return
     */
    @Override
    public UserLoginVo login(User user) {
        //1、查询用户
        User userInfo = userMapper.login(user);

        //2、如果能查询到，则生成令牌
        if(userInfo!=null){
            //将第1个参数的属性值，复制给第2个参数
            UserLoginVo vo = new UserLoginVo();
            BeanUtils.copyProperties(userInfo,vo);
            //生成token令牌
            Map<String,Object> payload = new HashMap<>();
            payload.put("id",userInfo.getId());
            payload.put("username",userInfo.getUsername());
            payload.put("name",userInfo.getName());
            String token = JwtUtils.generateJwt(payload);
            vo.setToken(token);
            return vo;
        }
        //3、否则返回null
        return null;
    }

    @Override
    public void update(User user) {
        userMapper.update(user);
    }

    /***
     * 分页查询
     *      0）使用封装对象PageQuery接收前端传入的条件
     *      1）查询总数量     【有条件】->动态SQL
     *      2）分页查询      【有条件】->动态SQL
     *      3）响应数据->封装PageResult对象（分页）
     *          分页数据
     *          列表数据
     */
    @Override
    public PageResult page(PageQuery<User> pageQuery) {
        //1）查询总数量     【有条件】->动态SQL
        User user = pageQuery.getBody();
        long total = userMapper.count(user);
        //2）分页查询      【有条件】->动态SQL   limit #{索引},#{每页的条数}
        List<User> list = userMapper.list(pageQuery);

        int pages = (int) (total%pageQuery.getPageSize()==0? total/pageQuery.getPageSize():total/pageQuery.getPageSize()+1);
        PageResult pageResult = PageResult.builder()
                .currentPage(pageQuery.getPage())
                .total(total)
                .pages(pages)
                .build();
        //集合数据
        pageResult.setData(list);
        return pageResult;
    }


}
